package middlewave

import (
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"runtime"
	"backend/constants/errorCode"
	"backend/utils"
)

// HandleError
// 错误处理中间件
func HandleError(ctx *context.Context,cfg *web.Config){
	if err := recover(); err != nil {
		if !cfg.RecoverPanic {
			panic(err)
		}
		var result interface{}
		data := make(map[string]interface{})
		logs.Error(err)
		var stack string
		logs.Critical("the request url is ", ctx.Input.URL())
		logs.Critical("Handler crashed with error", err)
		for i := 1; ; i++ {
			_, file, line, ok := runtime.Caller(i)
			if !ok {
				break
			}
			logs.Critical(fmt.Sprintf("%s:%d", file, line))
			stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
		}
		data["type"] = "program"
		data["url"] = ctx.Input.URL()
		data["panic"] = fmt.Sprint(err)
		result = errorCode.Err500.WithData(data)
		str := utils.Strval(result)
		ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
		ctx.WriteString(str)
	}
}

// HandleGoroutineError
// 协程错误处理中间件
func HandleGoroutineError(){
	if err := recover(); err != nil {
		logs.Error(err)
		var stack string
		logs.Critical("the error type is goroutine")
		logs.Critical("Handler crashed with error", err)
		for i := 1; ; i++ {
			_, file, line, ok := runtime.Caller(i)
			if !ok {
				break
			}
			logs.Critical(fmt.Sprintf("%s:%d", file, line))
			stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
		}
	}
}